﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="销售订单号" prop="SaleOrdeCode">
              <SoOrderSelect
                v-model="entity.SaleOrdeCode"
                @change="changeselect"
                :disabled="title !== '新建'"
              ></SoOrderSelect>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户" prop="CusName">
              <a-input v-model="entity.CusName" autocomplete="off" placeholder="客户" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户地址" prop="CustomerAddress">
              <a-input v-model="entity.CustomerAddress" autocomplete="off" placeholder="客户地址" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="单据日期" prop="DeliveryTime">
              <a-input v-model="entity.DeliveryTime" autocomplete="off" placeholder="单据日期" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" prop="Memo">
              <a-input v-model="entity.Memo" autocomplete="off" placeholder="备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div style="position: relative;">
        <a-button
          :style="{ marginRight: '8px' }"
          type="primary"
          @click="addMaterial"
          v-if="title != '审核' && title != '查看'"
          style="margin-right: 10px;position: absolute;right: 0;top: 13px;z-index: 999;"
        >添加物品</a-button
        >

        <a-tabs default-active-key="1">
          <a-tab-pane key="1" tab="物品明细">
            <a-table
              :columns="title === '查看' ? columnslook : columns"
              :data-source="dataArr"
              :loading="loading"
              :pagination="false"
              :rowKey="(row, index) => row.RowId"
              size="small"
              bordered
            >
              <template slot="StockVolume" slot-scope="text, record, index">
                <a-input
                  size="small"
                  type="number"
                  v-model="record.StockVolume"
                  @change="StockVolumechange($event, record)"
                  :disabled="title === '新建' ? false : title === '编辑' ? false : true"
                  style="width: 100%; text-align: right"
                ></a-input>
              </template>

              <template slot="action" slot-scope="text, record, index">
                <a-popconfirm
                  title="确定删除吗?"
                  @confirm="() => del(record, index)"
                  v-if="title === '新建' || title === '编辑'"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
              <template slot="dataIndex" slot-scope="text, record, index">
                <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
      <div style="height: 60px;"></div>
    </a-spin>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '4px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            this.visible = false
          }
        "
      >取消</a-button
      >
      <a-button type="primary" v-if="title == '审核'" @click="Review" :loading="loading">审核通过</a-button>
      <a-button
        type="primary"
        v-if="title != '审核' && title != '查看'"
        @click="handleSubmit"
        :loading="loading"
      >保存</a-button
      >
    </div>
    <MaterialChoose ref="MaterialChoose" @onChoose="handleChoose"></MaterialChoose>
  </a-drawer>
</template>

<script>
import SoOrderSelect from './SoOrderSelect.vue'
import MaterialChoose from './materialChoose'
export default {
  props: {
    parentObj: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  components: {
    SoOrderSelect,
    MaterialChoose
  },
  data () {
    return {
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      disabled: true,
      loading: false,
      dataArr: [],
      entity: {},
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'],
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize)
      },
      columnslook: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'dataIndex' },
          width: '50px'
        },
        { title: '编号', dataIndex: 'MaterialCode', ellipsis: true },

        { title: '名称', dataIndex: 'MaterialName' },
        {
          title: '规格',
          dataIndex: 'MaterialSpec',

          ellipsis: true
        },
        {
          title: '单位',
          dataIndex: 'UnitGroupName'
        },
        {
          title: '分类名称',
          dataIndex: 'MaterialTypeName'
        },
        {
          title: '库存可用数量',
          dataIndex: 'SurplusNums',
          align: 'right'
        },
        {
          title: '分类剩余发货数量',
          dataIndex: 'SurplusQuantity',
          align: 'right'
        },
        {
          title: '已发货数量',
          dataIndex: 'ReadyNums',

          align: 'right'
        },
        {
          title: '发货数量',
          dataIndex: 'StockVolume',
          scopedSlots: { customRender: 'StockVolume' },
          align: 'right'
        },
        {
          title: '批次号',
          dataIndex: 'Batch'
        },
        { title: '到期天数', dataIndex: 'ExpireNum', align: 'right' }
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'dataIndex' },
          width: '50px'
        },
        { title: '编号', dataIndex: 'MaterialCode', ellipsis: true },

        { title: '名称', dataIndex: 'MaterialName' },
        {
          title: '规格',
          dataIndex: 'MaterialSpec',

          ellipsis: true
        },
        {
          title: '单位',
          dataIndex: 'UnitGroupName'
        },
        {
          title: '订单数量',
          dataIndex: 'Quantity',
          align: 'right'
        },
        {
          title: '库存可用数量',
          dataIndex: 'SurplusNums',
          align: 'right'
        },
        {
          title: '剩余发货数量',
          dataIndex: 'SurplusQuantity',
          align: 'right'
        },

        {
          title: '发货数量',
          dataIndex: 'StockVolume',
          scopedSlots: { customRender: 'StockVolume' },
          align: 'right'
        },
        {
          title: '批次号',
          dataIndex: 'Batch'
        },
        { title: '到期天数', dataIndex: 'ExpireNum', align: 'right' },

        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } }
      ],
      rules: {
        SaleOrdeCode: [{ required: true, message: '请选择物品申请单', trigger: 'blur' }],
        DeliveryTime: [{ required: true, message: '请选择单据日期', trigger: 'change' }]
      },
      title: ''
    }
  },
  methods: {
    init () {
      this.visible = true
      this.entity = {}
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    openForm (id, title) {
      this.init()
      this.title = title
      if (id) {
        this.loading = true
        this.$http.post('/PB/PB_ShippingNotice/GetTheData', { id: id }).then(resJson => {
          this.loading = false
          this.entity = resJson.Data
        })
      }
    },
    close () {
      this.visible = false
      for (let index = 1; index < 5; index++) {
        this['data' + index] = []
      }
      this.entity = {}
    },
    Review () {
      this.$confirm({
        title: '确认审核通过吗?',
        onOk: () => {
          this.loading = true
          this.$http.post(`/PB/PB_PickUpMain/SaveToExamine?PickUpMainId=${this.Id}&Status=1`, {}).then(resJson => {
            if (resJson.Success) {
              this.visible = false
              this.$message.success('操作成功!')
              this.parentObj.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
            this.loading = false
          })
        }
      })
    },
    handleChoose (a) {
      console.log(a)
      this.loading = true
      a.forEach(item => {
        // if (Number(item.SurplusNums) < Number(item.SurplusQuantity)) {
        //   this.$set(item, 'StockVolume', item.SurplusNums)
        // } else {
        //   this.$set(item, 'StockVolume', item.SurplusQuantity)
        // }
        this.$set(item, 'StockVolume', '')
        this.$set(item, 'rowspan', null)
      })
      a = [...this.dataArr, ...a]
      var newobj = {}
      // reduce 方法
      var maparr = []
      a = a.reduce((preVal, curVal) => {
        if (!newobj[curVal.RowId]) {
          // 如果这个对象里面没有对应的ID 就push进新数组 并给此ID赋值下次判断有这个ID就说明是重复
          preVal.push(curVal)
          newobj[curVal.RowId] = curVal.RowId
        } else {
          // 如果有对应的ID就说明重复 数组里面有重复对象的MaterialId,添加到另外一个数组是重复的对象
          maparr.push(curVal)
        }
        return preVal
      }, [])
      if (maparr.length > 0) {
        this.$message.error('重复物品已筛选掉')
      }
      console.log(a, maparr)
      this.dataArr = this.checkSameData(a, 'MaterialCode')
      // this.dataArr = [...a]

      this.loading = false
    },
    StockVolumechange (eve, row) {
      if (row.StockVolume.split('.').length > 1) {
        this.$message.error('不能填写小数点')
        row.StockVolume = Math.floor(Number(row.StockVolume))
        return
      }
      if (Number(row.SurplusNums) > Number(row.SurplusQuantity)) {
        if (Number(row.StockVolume) > Number(row.SurplusQuantity)) {
          this.$message.error('发货数量不能大于分类剩余发货数量')
          this.$set(row, 'StockVolume', row.SurplusQuantity)
        }
      } else {
        if (Number(row.StockVolume) > Number(row.SurplusNums)) {
          this.$message.error('发货数量不能大于可用数量')
          this.$set(row, 'StockVolume', row.SurplusNums)
        }
      }
    },
    addMaterial () {
      if (this.entity.SaleOrdeCode) {
        this.$refs.MaterialChoose.openChoose(this.entity.SaleOrderId, this.dataArr)
      } else {
        this.$message.error('请选择销售订单后添加物品')
      }
    },
    del (row, index) {
      this.dataArr.splice(index, 1)
      this.loading = true
      this.dataArr = this.checkSameData(this.dataArr, 'MaterialCode')
      this.loading = false
    },
    changeselect (row) {
      console.log(row)
      this.$set(this.entity, 'CusName', row.cCusName)
      this.$set(this.entity, 'SaleOrderId', row.Id)
      this.$set(this.entity, 'CusID', row.cCusCode)
      this.$set(this.entity, 'CustomerAddress', row.cCusOAddress)
      this.$set(this.entity, 'SaleOrdeCode', row.cSOCode)
      this.dataArr = []
    },
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        this.$http.post('/PB/PB_ShippingNotice/SaveData', this.entity).then(resJson => {
          this.loading = false
          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.loading = false
            this.visible = false
	          this.$emit('returnMain')
          } else {
            this.$message.error(resJson.Msg)
            this.loading = false
          }
        })
      })
    },
    // 非空校验
    validEmpty (index, name, tips) {
      return (rule, value, callback) => {
        const data = this.DetaiData[index][name]
        if (!data) {
          this.$message.warning('列表第' + (index + 1) + '行：' + tips)
          callback(tips || '必填')
        } else {
          callback()
        }
      }
    }
  }
}
</script>
<style scoped>
</style>
